package com.leo.producer;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.lang.reflect.Type;

@SpringBootApplication
public class LeoProducerApplication {
    public static void main(String[] args) {
        SpringApplication.run(LeoProducerApplication.class, args);
    }

    /**
     * 配置消息转换器
     */
    @Bean
    public MessageConverter messageConverter() {
        // 定义消息转换器

        Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter(){
            /**
             * 消息转换器，用于将消息转换成对象
             */
            @Override
            public Object fromMessage(Message message) throws MessageConversionException {
                Object header = message.getMessageProperties().getHeader("user-info");
                if (header != null){
                    System.out.println("消息头 -> " + header);
                }
                return super.fromMessage(message);
            }
            /**
             * 创建消息，并添加头信息
             */
            @Override
            protected Message createMessage(Object objectToConvert, MessageProperties messageProperties, Type genericType) throws MessageConversionException {
                // 给message，添加头信息
                messageProperties.setHeader("user-info", 666L);
                return super.createMessage(objectToConvert, messageProperties, genericType);
            }
        };
        // 配置自动创建消息ID，用于识别不同消息，也可在业务中基于ID判断是否是重复消息
        converter.setCreateMessageIds(true);
        return converter;
    }

}
